﻿using Common.Library.Db;
using Common.Library.Logs;
using Common.Library.StringExt.Randoms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 解决用户表中重复数据问题
{
    class Program
    {
        public static Queue<IdCardEntity> idQueue = new Queue<IdCardEntity>();
        public static Queue<string> logQueue = new Queue<string>();
        static SqlServerLog logserver = new SqlServerLog();

        static void Main(string[] args)
        {
            IAppDBContext appDb = AppDBContextFactory.GetAppDBContext();
            SqlServerLog log = new SqlServerLog();
            List<string> phoneList1 = new List<string>();

            #region 身份证号重复问题
            {
                DataQuqueIdCard();
                Task.Run(() =>
                {
                    ///获取1000条身份证重复的数据
                    ///分给五个线程去处理这些问题
                    ///在打开一个线程用向队列中插入数据
                    ///在开一个线程用来记录日志
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            SetIdCard();
                        }
                    });
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            SetIdCard();
                        }
                    });
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            SetIdCard();
                        }
                    });
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            SetIdCard();
                        }
                    });
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            SetIdCard();
                        }
                    });
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            DataQuqueIdCard();
                        }
                    });
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            WriteLog();
                        }
                    });
                });
            }
            #endregion

            Console.ReadLine();
            #region 手机号重复问题
            {
                //                string sql = @" select phone,count(phone) as 'count' from userinfo 
                //group by phone
                //having Count(phone) > 2";
                //                string msg = "";
                //                string tempPhone = "";
                //                List<UserPhoneModel> phoneList = appDb.Get<UserPhoneModel>(sql).ToList();
                //                phoneList1 = appDb.Get<string>("select distinct phone from userinfo ").ToList();
                //                foreach (UserPhoneModel item in phoneList)
                //                {
                //                    sql = " select Id from userinfo where phone = '" + item.phone + "'";
                //                    List<UserInfoId> idList = appDb.Get<UserInfoId>(sql, null).ToList();
                //                    for (int i = 1; i < item.count; i++)
                //                    {
                //                        tempPhone = RandomMoble.GetMoble();
                //                        bool flag = true;
                //                        while (flag)
                //                        {
                //                            if (!phoneList1.Contains(tempPhone))
                //                            {
                //                                flag = false;
                //                            }
                //                            else
                //                            {
                //                                tempPhone = RandomMoble.GetMoble();
                //                            }
                //                        }
                //                        sql = " update dbo.userinfo set phone = " + tempPhone + " where id = " + idList[i].Id;
                //                        appDb.ExecuteCommand(sql);
                //                        msg = $"用户Id 为: { idList[i].Id } 的手机号，从 { item.phone } 修改成 { tempPhone }";
                //                        log.WriteLog(SystemType.Job_重置用户信息, ErrorType.系统日志, System.Reflection.MethodInfo.GetCurrentMethod().Name, "", msg);
                //                    }
                //                }
            }
            #endregion

        }

        /// <summary>
        /// 记录日志
        /// </summary>
        static void WriteLog()
        {
            if (logQueue.Count <= 0)
            {
                Thread.Sleep(2000);
            }
            else
            {
                logserver.WriteLog(SystemType.Job_重置用户身份证号, ErrorType.系统日志, System.Reflection.MethodInfo.GetCurrentMethod().Name, "", logQueue.Dequeue());
            }
        }

        //sat

        static void SetIdCard()
        {
            if (idQueue.Count <= 0)
            {
                Thread.Sleep(2000);
            }
            else
            {
                try
                {
                    var entitiy = idQueue.Dequeue();
                    while (entitiy != null)
                    {
                        if (idQueue.Count <= 10)
                        {
                            Thread.Sleep(2000);
                        }
                        entitiy = idQueue.Dequeue();
                    }
                    string idCard = IDCardNumber.Radom();
                    string sql = $"select COUNT(idcrde) from userinfo  where idcrde = '{ idCard }'";
                    bool flag = true;
                    while (flag)
                    {
                        if (AppDBContextFactory.GetAppDBContext().Get<int>(sql).FirstOrDefault() == 0)
                        {
                            flag = false;
                        }
                        else
                        {
                            idCard = IDCardNumber.Radom();
                        }
                    }
                    entitiy.Id = AppDBContextFactory.GetAppDBContext().Get<int>($"select id from userinfo  where idcrde = '{ entitiy.IdCrde }'").FirstOrDefault();
                    sql = $"update userinfo set idcrde = '{ idCard }' where id = " + entitiy.Id;
                    AppDBContextFactory.GetAppDBContext().ExecuteCommand(sql);
                    logQueue.Enqueue($"刷新用户身份证号：用户Id: { entitiy.Id } , 用户原有身份证号: { entitiy.IdCrde } , 刷新成: { idCard }");
                }
                catch (Exception ex)
                {
                    logserver.WriteLog(SystemType.Job_重置用户身份证号, ErrorType.异常BUG, System.Reflection.MethodInfo.GetCurrentMethod().Name, "", ex.Message);
                }
            }
        }

        /// <summary>
        /// 数据加入队列
        /// </summary>
        static void DataQuqueIdCard()
        {
            if (idQueue.Count <= 10000)
            {
                List<IdCardEntity> idCardList = AppDBContextFactory.GetAppDBContext().Get<IdCardEntity>(@"select top 1000 idcrde,COUNT(idcrde) from userinfo 
group by idcrde
having COUNT(idcrde) > 2").ToList();
                foreach (var item in idCardList)
                {
                    idQueue.Enqueue(item);
                }
            }
            else
            {
                Thread.Sleep(1000);
            }
        }
    }
}
